//
// Copyright (c) 2009-2011, chunquedong
//
// This file is part of ChunMap project
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
//
// History:
//   2011-12-04  Jed Young  Creation
//

using chunmapModel
using chunmapData
using chunmapView
using slanData
using slanOrm

**
** Insert shapefile to database
**
class ShpToDb
{
  Context? c
  ConnFactory? factory
  QuartTreeIndex? index

  Void open(Schema table)
  {
    factory = ConnFactory.make(ShpToDb#.pod)
    tables := Mapping([table])
    c = Context(tables)
    factory.open
  }

  Void close()
  {
    factory.close
  }

  private Schema changeSchema(Schema old)
  {
    list := CField[,]
    old.each |f|
    {
      list.add(f)
    }
    id := CField("fid", Int#, old.size)
    geometry := CField("geometry", Buf#, old.size+1)
    skey := CField("skey", Str#, old.size+2)

    list.add(id).add(geometry).add(skey)

    return Schema(old.name, list)
  }

  private Record changeRecord(Schema ns, ShapeFeature old)
  {
    values := [,]
    (ns.size-3).times |i|
    {
      values.add(old.get(i))
    }

    values.add(old.id)

    buf := Buf()
    old.geometry.save(buf.out)
    buf.flip
    values.add(buf)

    values.add(index.key(old.geometry.envelope))

    nr := Record(ns, values)
    return nr
  }

  **
  ** main
  **
  Void main()
  {
    index = QuartTreeIndex(Envelope(-180f, -90f, 180f, 90f))
    layer0 := VectorLayer.makeUri((this.typeof->sourceFile.toStr.toUri + `../data/cntry02/cntry02.shp`))
    featureSet := layer0.dataSource as FeatureSet

    Schema? ns
    featureSet.each(Condition.empty) |ShapeFeature f|
    {
      if (ns == null)
      {
        ns = changeSchema(f.schema)
        open(ns)

        if (c.tableExists(ns))
        {
          c.dropTable(ns)
        }
        c.createTable(ns)
      }
      nf := changeRecord(ns, f)
      c.insert(nf)
      echo(f)
    }

    close
  }
}